#coding=utf8
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from google.appengine.ext import webapp
from google.appengine.api import xmpp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
import google.appengine.api.urlfetch
import google.appengine.api.users as users
import logging
import traceback
import os
import common
import gaetwitter
import sys

class MainPage(webapp.RequestHandler):
    def get(self):
        template_values = {}
        user = users.get_current_user()
        common.update_user_varible(template_values)
        #isbinding
        bindEntry = gaetwitter.getBindingEntry(user)
        template_values['isbinding'] = bindEntry!=None
        if bindEntry:
            template_values['twitter_username'] = bindEntry.twitter_username
        
                
        path = os.path.join(os.path.dirname(__file__), 'template/main.html')
        self.response.out.write(template.render(path, template_values))

class BindingPage(webapp.RequestHandler):
    msg=''
    def get(self):
        template_values = {}
        user = users.get_current_user()
        if user == None:
            self.redirect('/')
            return
        common.update_user_varible(template_values)
        bindEntry = gaetwitter.getBindingEntry(user)
        template_values['isbinding'] = bindEntry!=None
        template_values['msg'] = self.msg
        if bindEntry:
            template_values['twitter_username'] = bindEntry.twitter_username
        
        path = os.path.join(os.path.dirname(__file__), 'template/binding.html')
        self.response.out.write(template.render(path, template_values))
    def post(self):
        twitter_username = self.request.POST['twitter_username']
        twitter_password = self.request.POST['twitter_password']
        try:
            twuser = gaetwitter.verityTwitterAccount(twitter_username,twitter_password)
        except gaetwitter.TwitterError:
            twuser = None
        if twuser == None:
            self.msg = 'Twitter账号验证错误，请重新绑定'
            self.get()
            return
        else:
            self.msg = ''
            gaetwitter.bindTwitterAccount(users.get_current_user(),twitter_username,twitter_password)
            self.response.out.write('''
            <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
            <meta http-equiv="refresh" content="1;url=/" />
            绑定成功，自动返回<a href="/">首页</a>''')
            
class UnbindPage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            gaetwitter.unbindTwitterAccount(user)
        self.redirect('/')

class XMPPHandler(webapp.RequestHandler):
    def post(self):
        msg = self._message = xmpp.Message(self.request.POST)
        logging.info(u'%s:%s'%(msg.sender,msg.body))
        cmd = msg.command
        sender = msg.sender
        slash_pos = sender.find(u'/')
        if slash_pos>=0:
            sender = sender[:slash_pos]
        self._sender = sender
        self._user = users.get_current_user()
        if self._user == None:
            self._user = users.User(sender)
        self._bindingEntry = gaetwitter.getBindingEntry(self._user)
        #logging.info('_bindingEntry:'+str(self._bindingEntry))
        try:
            self.process_command()
        except gaetwitter.TwitterError:
            _,exc_val,_ = sys.exc_info()
            self._message.reply(u'TwitterError:'+exc_val.message)
        except google.appengine.api.urlfetch.DownloadError:
            self._message.reply(u'DownloadError:'+u'...')
            logging.error(u'error command:'+msg.body)
            logging.error(traceback.format_exc())
        except:
            self._message.reply(u'Unknown error')
            logging.error(u'error command:'+msg.body)
            logging.error(traceback.format_exc())
            

    def process_command(self):
        msg = self._message
        cmd = msg.command
        arg = msg.arg
        if cmd==u'eval' and users.is_current_user_admin():
            self.do_eval(arg)
            return
        
        if self._bindingEntry == None:
            if cmd == u'bind':
                self.do_bind(arg)
            else:
                self.show_help_for_unbind()
        else:
            if cmd == u'bind':
                self.do_bind(arg)
            elif cmd == u'unbind':
                self.do_unbind(arg)
            elif cmd == u'update':
                self.do_update(arg)
            elif cmd == u'follow':
                self.do_follow(arg)
            elif cmd == u'unfollow':
                self.do_unfollow(arg)
            else:
                self.show_helps()
    
    def show_help_for_unbind(self):
        self._message.reply(u'Hello,I\'m twitter gtalk bot.\nuse "/bind <twitter username> <twitter password>" to bind account.\nMore info:http://twittertalk001.appspot.com')
    
    def show_helps(self):
        self._message.reply(u'this is help')
    
    def do_update(self,arg):
        help_msg = '更新状态\n语法：/update <状态>\n例如：/update 天气真好'
        arg = arg.strip()
        if arg==u'':
            self._message.reply(help_msg)
        else:
            api = gaetwitter.createApi(self._bindingEntry.twitter_username,self._bindingEntry.twitter_password)
            api.PostUpdate(arg)
    
    def do_follow(self,arg):
        help_msg = '跟随某人\n语法：/follow <user>'
        arg = arg.strip()
        if not arg:
            self._message.reply(help_msg)
        else:
            api = gaetwitter.createApi(self._bindingEntry.twitter_username,self._bindingEntry.twitter_password)
            user = api.CreateFriendship(arg)
            self._message.reply(u'成功跟随%s(%s)'%(user.screen_name,user.name))
    
    def do_unfollow(self,arg):
        help_msg = '离开某人\n语法：/unfollow <user>'
        arg = arg.strip()
        if not arg:
            self._message.reply(help_msg)
        else:
            api = gaetwitter.createApi(self._bindingEntry.twitter_username,self._bindingEntry.twitter_password)
            user = api.DestroyFriendship(arg)
            self._message.reply(u'成功离开%s(%s)'%(user.screen_name,user.name))
    
    def do_eval(self,arg):
        try:
            reply = eval(arg)
        except:
            reply = traceback.format_exc()
        self._message.reply(reply)
    
    def do_unbind(self,arg):
        help_msg = u'取消账号绑定\n语法：/unbind'
        if arg.strip()!=u'':
            self._message.reply(help_msg)
        else:
            gaetwitter.unbindTwitterAccount(self._user)
            self._message.reply(u'成功取消账号绑定')
            
    def do_bind(self,arg):
        help_msg = u'绑定账号\n语法：/bind <twitter username> <twitter password>\n例如：/bind xxx@xxx.com 123456'
        sp_pos = arg.find(u' ')
        if sp_pos>=0:
            username = arg[:sp_pos].strip()
            password = arg[sp_pos+1:].strip()
            if username and password:
                try:
                    user = gaetwitter.verityTwitterAccount(username,password)
                except gaetwitter.TwitterError:
                    self._message.reply(u'Twitter账号验证失败，绑定失败')
                    return
                else:
                    if user == None:
                        self._message.reply(u'Twitter账号验证失败，绑定失败')
                        return
                    else:
                        gaetwitter.bindTwitterAccount(self._user,username,password)
                        self._message.reply(u'绑定账号成功')
                        return
        self._message.reply(help_msg)
            

application = webapp.WSGIApplication([
  ('/', MainPage),
  ('/binding',BindingPage),
  ('/unbind',UnbindPage),
  ('/_ah/xmpp/message/chat/', XMPPHandler)
], debug=True)


def main():
    run_wsgi_app(application)


if __name__ == '__main__':
    main()
